package com.smartsofa.main;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.adapter.SearchUserAdapter;
import com.smartsofa.util.MyUtils;

public class AddFamilyMember extends Activity {
	
	private Button bt_back;
	private EditText search_info;
	private Button bt_addmember;
	private ListView lv_search_result;
	
	private Intent intent;
	private int familyId;
	private SearchUserAdapter adapter;
	
	private ProgressDialog mDialog;
	private String url;
	private Boolean flag=false;
	private String reg_msg;
	private JSONObject json;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_family_member);
		Bundle bundle=getIntent().getExtras();
		familyId=Integer.valueOf(bundle.getString("familyId"));
		initView();
	}
	
	private void initView(){
		bt_back=(Button) findViewById(R.id.back);
		bt_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AddFamilyMember.this.finish();
			}
		});
		search_info=(EditText)findViewById(R.id.search_info);
		bt_addmember=(Button)findViewById(R.id.bt_addmember);
		lv_search_result=(ListView)findViewById(R.id.lv_search_result);
		bt_addmember.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String search=search_info.getText().toString();
				if(search.equals(null)||search.trim().equals("")){
					Toast.makeText(AddFamilyMember.this, "搜索的内容不能为空！", Toast.LENGTH_SHORT).show();
				}
				else{
			    	mDialog = new ProgressDialog(AddFamilyMember.this);
					mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
					mDialog.setMessage("搜索中，请稍候...");
					mDialog.show();
					Thread thread=new Thread(new search_thread(search));
					thread.start();
				}
			}
		});
	}
	class search_thread implements Runnable{
		String search;
		public search_thread(String search){
			this.search=search;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				url=MyUtils.getUrl()+"family_searchUser?search="+search;
				HttpGet request = new HttpGet(url);																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);					       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	  network_timeout=true;
		          String jsonString = EntityUtils.toString(httpResponse.getEntity());
		          json = new JSONObject(jsonString);
		          flag=json.getBoolean("success");
		          reg_msg=json.getString("msg");
		          Message msg = content_handler.obtainMessage();
					if(network_timeout){
						if (flag) {				
							msg.what = 1;
							
						}else{
							msg.what = 2;			
						}
					}			
					else{
						msg.what = 3;						
					}
					content_handler.sendMessage(msg);
		         
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		     }
		}
		
	}
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {	
			mDialog.dismiss();
			switch (msg.what) {		
			case 1:	
		     	try {
					JSONArray jsonarr=json.getJSONArray("obj");
					adapter=new SearchUserAdapter(getApplicationContext(), getData(jsonarr),familyId);
					lv_search_result.setAdapter(adapter);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		     	break;
			case 2:
				Toast.makeText(AddFamilyMember.this,reg_msg.toString(),Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(AddFamilyMember.this,"网络连接超时!",Toast.LENGTH_SHORT).show();
				break;
		     }
		}
	};
	/**
	 * 获取数据
	 * @throws JSONException 
	 */
	private List<Map<String, Object>> getData(JSONArray jsonarr) throws JSONException{	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	    for(int i=0;i<jsonarr.length();i++)  
           {  			    	   
               HashMap<String, Object> map = new HashMap<String, Object>();  
              
			   map.put("userImg", jsonarr.getJSONObject(i).get("userImg"));
			   map.put("userName", jsonarr.getJSONObject(i).get("userName")); 
               map.put("userID", jsonarr.getJSONObject(i).get("userID"));
               map.put("cellphone", jsonarr.getJSONObject(i).get("cellphone"));
               map.put("sex", jsonarr.getJSONObject(i).get("sex"));
               map.put("deviceID", jsonarr.getJSONObject(i).get("deviceID"));
               
               list.add(map);
           }
	    Log.i("list:", list.toString());
	    return list;
	}
}
